<template>
  <div class="home-root">
    <!-- 在 .home-root 容器内添加刷新按钮 -->
    <div class="refresh-button" @click="refreshPage">
      <img :src="refreshIcon" alt="刷新"/>
    </div>

    <!-- 添加指南针方向指示器 -->
    <div class="compass-container">
      <div class="compass">
        <div class="compass-direction n">N</div>
        <div class="compass-direction e">E</div>
        <div class="compass-direction s">S</div>
        <div class="compass-direction w">W</div>
        <div class="compass-needle north"></div>
        <div class="compass-needle south"></div>
        <div class="compass-center"></div>
      </div>
    </div>


    <TopDrawer
        :visible="showTopDrawer"
        :startPoint="startPointData"
        :endPoint="endPointData"
        @clear-points="clearPointsAndMarkers"
    />

    <!-- 快捷入口抽屉 -->
    <BottomDrawer
        :visible="showBottomDrawer"
        :height="drawerHeight"
        :doorNum="currentRoomDoorNum"
        @update:height="onDrawerHeightChange"
    />
    <!--    <QuickEntry :doorNum="currentRoomDoorNum" />-->


    <BottomDrawer2
        :visible="showBottomDrawer2"
        :start-point="startPointData"
        :end-point="endPointData"
        :distance="pathDistance"
        :duration="pathDuration"
        :navigation-tips="pathTips"
        :is-same-floor="isSameFloor"
        @switch-floor="switchToTargetFloor"
        @height-change="handleBottomDrawer2HeightChange"
    />


    <BottomDrawer3
        :visible="showBottomDrawer3"
        :room-name="roomName"
        :room-id="roomId"
        @close="() => { showBottomDrawer3 = false;}"
        @set-end="setEndPointFromRoom_click"
    />

    <FloorSwitch
        ref="floorSwitchRef"
        :bottomOffset="bottomOffset"
        :hide="hideFloorSwitch"
        @floor-change="handleFloorChange"
        style="position: fixed; left: 10px; z-index: 10000;"
    />

    <div class="leaflet-container">
      <div id="map"></div>
    </div>
  </div>
</template>

<script>
import "leaflet/dist/leaflet.css";
import {computed, onMounted, ref, shallowRef, watch, nextTick} from "vue";
import L from "leaflet";
import GeoJsonPathFinder from "geojson-path-finder";
import * as turf from "@turf/turf";
import {useRoute, useRouter} from 'vue-router'
import FloorSwitch from '@/components/floorSwitch/FloorSwitch.vue';
import BottomDrawer from '@/components/drawer/quickEntryDrawer.vue';
import BottomDrawer2 from "@/components/drawer/navigationDrawer.vue";
import BottomDrawer3 from "@/components/drawer/tipMessageDrawer.vue";
import TopDrawer from "@/components/drawer/TopDrawer.vue";
import QuickEntry from "@/components/quickEntry/QuickEntry.vue";
import stairIconImage from "/img/stair.png";
// ✅ 添加导入语句
import {FLOOR_DATA, loadAllFloors} from '@/utils/getDataFromUrl'
import refreshIcon from '/img/refresh.png'
import parkingLotOut from '/img/parkingLotOut.png'
import parkingLotIn from '/img/parkingLotIn.png'
import {boolean} from "mockjs/src/mock/random/basic.js";
import {navy as pathfinder} from "mockjs";
import {get_floor, search_point} from "@/api/mock/index.js";

export default {
  name: "Index",
  components: {QuickEntry, BottomDrawer2, TopDrawer, FloorSwitch, BottomDrawer, BottomDrawer3},
  setup() {
    let index=-1;
    const roomName = ref('');
    const roomId = ref('');
    const map = shallowRef(null);
    const drawerHeight = ref(350);
    const bottomDrawer2Height = ref(120); // 默认高度
    const labelData = ref([]);
    const pathFinder = shallowRef(null);
    const drawnPath = shallowRef(null);
    const showTipMessageDrawer = ref(false);
    const showNavigationDrawer = ref(false);
    // const showQuickEntryDrawer = ref(true); // 删除这行
    const showTopDrawer = ref(false);
    const startPointData = ref({roomName: '', floor: null});
    const endPointData = ref({roomName: '', floor: null});
    const pathDistance = ref(0);
    const pathDuration = ref(0);
    const currentFloor = ref(null);
    const globalStartPoint = ref(null);
    const globalEndPoint = ref(null);
    const allFloorData = ref({});
    const stairMarker1 = shallowRef(null); // 起点楼层楼梯标记
    const stairMarker2 = shallowRef(null); // 终点楼层楼梯标记
    const startMarker = shallowRef(null);
    const endMarker = shallowRef(null);
    const route = useRoute()
    const router = useRouter()
    const id = ref(route.query.id)
    const pathTips = ref([]);
    const pendingTargetId = ref(null);
    const pendingTargetFloor = ref(null);
    const floorSwitchRef = ref(null);
    const F1_CENTER = [29.13044857858278, 119.63927150990025];

    const isSameFloor = computed(() => {
      if(startPointData.value.floor === endPointData.value.floor && startPointData.value.floor !== "F3"){
        return true;
      }else if(startPointData.value.floor === endPointData.value.floor && startPointData.value.floor === "F3"){
        return globalStartPoint.value.building === globalEndPoint.value.building;
      }else{
        return startPointData.value.floor === endPointData.value.floor;
      }

    });
    const layers = {
      waiKuangMian: null,
      danYuanMian: null,
      routeLine: null
    };// 地图图层
    // 这个函数作用是获取当前楼层的视图设置，如中心坐标和缩放级别。adjustmapViewForFloor函数用于根据给定的楼层名称，设置地图的视图。
    const floorViewSettings = {
      'F1': {
        center: [29.13290158492031, 119.6353427349051], // 中心点坐标 [纬度, 经度]
        zoom: 17
      },
      'F2': {
        center: [29.132813432064183, 119.63529222173739], // F2中心点坐标
        zoom: 17
      },
      'F3': {
        center: [29.132854671741278, 119.63531372482882], // F3中心点坐标
        zoom: 17
      },
      'F4': {
        center: [29.133222919506068, 119.63511320934183], // F4中心点坐标
        zoom: 17
      }
    };

    //新增代码
    async function getUserLocation() {
      return new Promise((resolve, reject) => {
        if (!navigator.geolocation) {
          reject(new Error('浏览器不支持地理位置'));
          return;
        }

        navigator.geolocation.getCurrentPosition(
            (position) => {
              resolve({
                lat: position.coords.latitude,
                lng: position.coords.longitude
              });
            },
            (error) => {
              reject(error);
            },
            {
              enableHighAccuracy: true,
              timeout: 10000,
              maximumAge: 60000
            }
        );
      });
    }

    function calculateDistance(userPos, targetPos) {
      // 使用 turf.js 计算两点间距离（单位：米）
      const from = turf.point([userPos.lng, userPos.lat]);
      const to = turf.point([targetPos[1], targetPos[0]]); // 注意经纬度顺序
      const distance = turf.distance(from, to, {units: 'meters'});
      return distance;
    }

    // 打开网页端导航
    function openWebNavigation(userPos,targetLat, targetLng, targetName) {
      // 提供多个导航选项
      const navOptions = [
        {
          name: "高德地图",
          url: `https://uri.amap.com/navigation?to=${targetLng},${targetLat},${encodeURIComponent(targetName)}&mode=walk`,
          icon: "📍",
          color: "#4b9eea" // Soft blue
        },
        {
          name: "百度地图",
          url: `http://api.map.baidu.com/direction?origin=${userPos.lat},${userPos.lng}&destination=latlng:${targetLat},${targetLng}|name:${encodeURIComponent(targetName)}&mode=walking&region=金华&output=html&coord_type=gcj02&src=webapp.demo.navigation`,
          icon: "🧭",
          color: "#4cc4b7" // Gentle teal
        },
        {
          name: "腾讯地图",
          url: `https://apis.map.qq.com/uri/v1/routeplan?type=walk&fromcoord=CurrentLocation&tocoord=${targetLat},${targetLng}&to=${encodeURIComponent(targetName)}&policy=1&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77`,
          icon: "🗺️",
          color: "#f28c8c" // Light coral
        }
      ];

      // 创建美化后的选择界面
      let navHtml = `    <div style="padding: 25px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; background: white; border-radius: 16px; box-shadow: 0 8px 16px rgba(0,0,0,0.15); color: #2d3748;">
    <div style="text-align: center; margin-bottom: 25px;">
      <div style="font-size: 36px; margin-bottom: 10px; color: #2d3748;">🧭</div>
      <h2 style="margin: 0 0 8px 0; font-weight: 600; font-size: 22px; color: #2d3748;">选择导航应用</h2>
      <p style="margin: 0; font-size: 15px; color: #4a5568;">请选择您要使用的导航应用</p>
    </div>
    <div style="display: flex; flex-direction: column; gap: 12px; margin-bottom: 20px;">
  `;

      navOptions.forEach((option, index) => {
        navHtml += `      <button id="nav-btn-${index}" style="
        display: flex;
        align-items: center;
        padding: 14px 18px;
        background: ${option.color};
        border: 1px solid rgba(0,0,0,0.1);
        border-radius: 10px;
        font-size: 16px;
        font-weight: 500;
        color: #1a202c;
        cursor: pointer;
        transition: all 0.2s ease;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      ">
        <span style="font-size: 22px; margin-right: 10px; color: #1a202c;">${option.icon}</span>
        <span>${option.name}</span>
        <span style="margin-left: auto; font-size: 16px; color: #1a202c;">›</span>
      </button>
    `;
      });

      navHtml += `      </div>
      <button id="nav-cancel" style="
        width: 100%;
        padding: 14px;
        background: #f7fafc;
        border: 1px solid #e2e8f0;
        border-radius: 10px;
        font-size: 16px;
        font-weight: 500;
        color: #2d3748;
        cursor: pointer;
        transition: all 0.2s ease;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      ">取消</button>
    </div>
  `;

      // 创建模态框
      const modal = document.createElement('div');
      modal.id = 'navigation-modal';
      modal.style.cssText = `    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10000;
    backdrop-filter: blur(4px);
    animation: fadeIn 0.3s ease-out;
  `;

      const modalContent = document.createElement('div');
      modalContent.style.cssText = `    max-width: 340px;
    width: 90%;
    animation: slideIn 0.3s ease-out;
  `;

      modalContent.innerHTML = navHtml;
      modal.appendChild(modalContent);
      document.body.appendChild(modal);

      // 添加动画样式
      const style = document.createElement('style');
      style.textContent = `    @keyframes fadeIn {
      from { opacity: 0; }
      to { opacity: 1; }
    }

    @keyframes slideIn {
      from {
        opacity: 0;
        transform: translateY(20px) scale(0.95);
      }
      to {
        opacity: 1;
        transform: translateY(0) scale(1);
      }
    }

    #navigation-modal button:hover {
      background: rgba(0,0,0,0.05) !important;
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    }

    #navigation-modal button:active {
      transform: translateY(0);
    }
  `;
      document.head.appendChild(style);

      // 添加事件监听器
      navOptions.forEach((option, index) => {
        const button = document.getElementById(`nav-btn-${index}`);
        button.addEventListener('click', () => {
          window.open(option.url, '_blank');
          document.body.removeChild(modal);
          if (document.head.contains(style)) {
            document.head.removeChild(style);
          }
        });

        // 添加悬停效果
        button.addEventListener('mouseenter', () => {
          button.style.boxShadow = '0 4px 8px rgba(0,0,0,0.15)';
        });

        button.addEventListener('mouseleave', () => {
          button.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)';
        });
      });

      document.getElementById('nav-cancel').addEventListener('click', () => {
        // 设置用户ID为507
        const newUserId = '507';
        // 通过URL参数设置新的ID并重新加载页面
        const url = new URL(window.location);
        url.searchParams.set('id', newUserId);
        window.location.href = url.toString();
      });

      // 点击模态框背景关闭
      modal.addEventListener('click', (e) => {
        if (e.target === modal) {
          document.body.removeChild(modal);
          if (document.head.contains(style)) {
            document.head.removeChild(style);
          }
        }
      });
    }

    // 检查用户位置并决定是否导航
    async function checkUserLocationAndNavigate() {
      try {

        // 添加一个小延迟，确保页面完全加载
        await new Promise(resolve => setTimeout(resolve, 1000));

        // 获取用户当前位置
        const userPos = await getUserLocation();

        // 计算与F1中心点的距离
        const distance = calculateDistance(userPos, F1_CENTER);

        // 如果距离大于500米，打开网页端导航选择
        if (distance > 500) {
          // 使用更友好的提示方式
          const shouldNavigate = confirm(`您当前位置距离目标位置约${Math.round(distance)}米，是否需要打开网页导航？`);

          if (shouldNavigate) {
            // 添加一个小延迟确保用户点击确认后再执行
            setTimeout(() => {
              openWebNavigation(userPos, F1_CENTER[0], F1_CENTER[1], "浙江师范大学-行政中心");
            }, 100);
          }
        } else {
          // 跳转到选择点页面
          router.push({name: 'ChoosePoint'}).catch(err => {
            console.error('路由跳转失败:', err);
          });
        }
      } catch (error) {
        console.error('获取位置信息失败:', error);

        // 提供更多帮助信息
        const userAction = confirm(
            `位置获取失败: ${error.message}\n\n` +
            `可能的解决方案:\n` +
            `1. 确保手机定位服务已开启\n` +
            `2. 在浏览器设置中允许位置权限\n` +
            `3. 刷新页面重试\n\n` +
            `是否要手动打开网页导航？`
        );

        if (userAction) {
          setTimeout(() => {
            openWebNavigation(F1_CENTER[0], F1_CENTER[1], "浙江师范大学-行政中心");
          }, 100);
        }
      }
    }

    //新增代码
    onMounted(async () => {
      try {
        // 确保DOM已更新
        await nextTick();

        // 加载所有楼层数据
        await loadAllFloors();
        console.log('所有楼层数据加载完成');

        // 确保地图容器存在
        const mapContainer = document.getElementById('map');
        if (!mapContainer) {
          console.error('地图容器不存在');
          return;
        }
        await loadAllFloors().then(() => {
          console.log('所有楼层数据加载完成');
        });
        map.value = L.map("map", {
          zoomSnap: 0.001,
          maxZoom: 23,
          minZoom: 18,
          zoomControl: false,
          scrollWheelZoom: false,
        });
        // 添加地图缩放事件监听
        map.value.on('zoomend', handleZoomChange);
        const start_id = id.value;
        localStorage.setItem('currentRoomDoorNum', start_id)
        // if (start_id === '1085' || start_id === '1086') {
        //   map.value.fitBounds([
        //     [29.132138209875976, 119.6352337993709],
        //     [29.133544972826883, 119.63613886372877]
        //   ], {
        //     paddingTopLeft: [10, 10],
        //     paddingBottomRight: [10, 10]
        //   });
        //
        // } else {
        //   map.value.fitBounds([
        //     [29.132164654034682, 119.63466056043131],
        //     [29.13356849127652, 119.63551388644998]
        //   ], {
        //     paddingTopLeft: [10, 10],
        //     paddingBottomRight: [10, 10]
        //   });
        // }

        // map.value.setZoom(19);
        // console.log("#####"+id.value);
        // console.log(typeof id.value);
        // console.log(typeof parseInt(id.value));


        // let response =  get_floor(id.value)
        //
        // console.log("#####"+JSON.stringify(response));
        // console.log(typeof response);
        // let floor ='F' + response.data;
        // console.log( floor)

        let floor = 'F';
        get_floor(id.value).then(response => {
          floor = 'F' + response.data;
          console.log("￥￥￥￥￥￥"+floor);
          adjustMapViewForFloor(floor);  // 楼层改变后，修改地图视角到中心位置

          if (FLOOR_DATA[floor]) {
            handleFloorChange({
              floorName: floor,
              geojsonData: FLOOR_DATA[floor].data
            });
          } else {
            console.error('缓存中未找到 floor 数据');
          }
          // 监听路由变化
          // 处理路由参数
          const startId = route.query.id;
          const targetId = route.query.targetId;
          const targetFloor = route.query.targetFloor;

          if (startId) {
            localStorage.setItem('currentRoomDoorNum', startId);
            // 延迟执行确保楼层数据已加载
            setTimeout(() => {
              setRoomById(startId);
            }, 100);
          }

          if (targetId && targetFloor) {
            // 设置终点
            setTimeout(() => {
              roomId.value = targetId;
              if (FLOOR_DATA[targetFloor]) {
                handleFloorChange({
                  floorName: targetFloor,
                  geojsonData: FLOOR_DATA[targetFloor].data
                });

                nextTick(() => {
                  setEndPointFromRoom();
                  if(globalStartPoint.value.floor === "F3" && globalEndPoint.value.floor === "F3" && globalStartPoint.value.building !== globalEndPoint.value.building){
                    switchToTargetFloor();
                    switchToTargetFloor();
                  }
                  if (
                      (globalStartPoint.value.floor ==="F4"
                          && globalEndPoint.value.floor === "F3"
                          && globalEndPoint.value.building === "南楼" )
                      ||
                      (globalEndPoint.value.floor ==="F4"
                          && globalStartPoint.value.floor === "F3"
                          && globalStartPoint.value.building === "南楼" )
                  ){
                    switchToTargetFloor();
                    switchToTargetFloor();
                    switchToTargetFloor();
                  }
                });
              }
            }, 200);
          }

          const savedDataStr = localStorage.getItem('mapData');
          if (savedDataStr) {
            try {
              const savedData = JSON.parse(savedDataStr);

              if (savedData.startPoint) {
                globalStartPoint.value = savedData.startPoint;
                startPointData.value = {
                  roomName: savedData.startPoint.roomName || '',
                  floor: savedData.startPoint.floor || null
                };
              }

              if (savedData.endPoint) {
                globalEndPoint.value = savedData.endPoint;
                endPointData.value = {
                  roomName: savedData.endPoint.roomName || '',
                  floor: savedData.endPoint.floor || null
                };
              }

              if (savedData.pathDistance !== undefined) {
                pathDistance.value = savedData.pathDistance;
              }

              if (savedData.pathDuration !== undefined) {
                pathDuration.value = savedData.pathDuration;
              }

              if (savedData.pathTips) {
                pathTips.value = savedData.pathTips;
              }

              if (savedData.currentFloor) {
                currentFloor.value = savedData.currentFloor;
              }

              // 如果当前楼层已加载，重新绘制路径和标记
              if (allFloorData.value[currentFloor.value]) {
                updateMarkersOnMap();
                if (globalStartPoint.value && globalEndPoint.value) {
                  calculateAndDrawPath(globalStartPoint.value, globalEndPoint.value);
                }
              }

            } catch (e) {
              console.error("恢复数据失败", e);
            }
          }

          // 初始调用一次，确保第一次加载就生效
          setTimeout(() => {
            handleZoomChange();
          }, 300);


        }).catch(error => {
          console.error("请求失败:", error);
        });

        // // handleFloorChange({
        // //   floorName: floor,
        // //   geojsonData: FLOOR_DATA[floor].data
        // // });

      } catch (error) {
        console.error('首页初始化过程中发生错误:', error);
      }
    });
    // 如果没有 id 参数，说明是统一二维码，需要检查用户位置
    if (!id.value) {
      // 延迟执行，确保地图初始化完成
      setTimeout(() => {
        checkUserLocationAndNavigate();
      }, 1000);
    }

    watchEffect(() => {
      drawerHeight.value = isSameFloor.value ? 100 : 350;
    });

    function handleBottomDrawer2HeightChange(height) {
      bottomDrawer2Height.value = height;
    }

    const bottomOffset = computed(() => {
      if (showNavigationDrawer.value) {
        return bottomDrawer2Height.value + 40; // 添加一些边距
      }
      // 当 BottomDrawer3 (即 showTipMessageDrawer) 显示时
      else if (showTipMessageDrawer.value) {
        return 120;
      }
      // 当 BottomDrawer (即 showQuickEntryDrawer) 显示时
      else if (showQuickEntryDrawer.value) {
        return drawerHeight.value + 8;
      }
      // 默认情况
      else {
        return 8;
      }
    });


    // 监听路由参数变化，处理搜索结果跳转
    watch(
        () => [route.query.targetId, route.query.targetFloor],
        ([newTargetId, newTargetFloor]) => {
          if (newTargetId && newTargetFloor) {
            pendingTargetId.value = String(newTargetId);
            pendingTargetFloor.value = String(newTargetFloor);

            // 关键：触发楼层切换到终点所在楼层，以便加载其地图数据
            if (floorSwitchRef.value && floorSwitchRef.value.loadFloorData) {
              floorSwitchRef.value.loadFloorData(newTargetFloor);
            } else {
              // 兜底方案
              if (FLOOR_DATA[newTargetFloor]) {
                handleFloorChange({
                  floorName: newTargetFloor,
                  geojsonData: FLOOR_DATA[newTargetFloor].data
                });
              } else {
                console.error('缓存中未找到 F1 数据');
              }
            }
          }
        },
        {immediate: true} // immediate:true 确保页面初始加载时也能执行
    );


    // 新增 computed 控制 quickEntryDrawer 显示
    const showQuickEntryDrawer = computed(() => {
      return !showNavigationDrawer.value && !showTipMessageDrawer.value;
    });


    //抽屉显示控制
    const isEndPointSet = computed(() => {
      return Boolean(endPointData.value.roomName);
    });// 判断终点是否已设置
    watch(isEndPointSet, (newVal) => {
      if (newVal) {
        showTopDrawer.value = true;
        // showQuickEntryDrawer.value = false; // 删除这行
        showNavigationDrawer.value = true;
      } else {
        showTopDrawer.value = false;
        // showQuickEntryDrawer.value = true; // 删除这行
        showNavigationDrawer.value = false;
      }
    });//监听 isEndPointSet 的变化，当其值为 true 时，显示顶部抽屉和提示信息抽屉，并隐藏快捷入口抽屉；反之则相反。
    const isStartPointSet = computed(() => {
      return Boolean(startPointData.value.roomName);
    });
    watch(isStartPointSet, (newVal) => {
      if (newVal) {
        // showQuickEntryDrawer.value = true; // 删除这行
      }
    })//监听 isStartPointSet 的变化，当其值为 true 时，显示快捷入口抽屉；反之则相反。
    watch(drawerHeight, (newVal) => {
      // drawerHeight 改变时自动触发 bottomOffset 的重新计算
      // 由于 bottomOffset 是 computed 属性，无需手动处理
    });

    function refreshPage() {
      const savedData = {
        startPoint: globalStartPoint.value,
        endPoint: globalEndPoint.value,
        pathDistance: pathDistance.value,
        pathDuration: pathDuration.value,
        pathTips: pathTips.value,
        currentFloor: currentFloor.value
      };
      localStorage.setItem('mapData', JSON.stringify(savedData));
      window.location.reload();
    }

    function switchToTargetFloor() {
      //点击切换楼层按键之后触发这个方法
      const startFloor = startPointData.value.floor;
      let endFloor = endPointData.value.floor;
      const midFloor = "F2";

      if (!startFloor || !endFloor) {
        console.warn("起点或终点楼层未定义");
        return;
      }

      let floorList = [startFloor, endFloor];
      if (
          (globalStartPoint.value.floor ==="F4"
          && globalEndPoint.value.floor === "F3"
          && globalEndPoint.value.building === "南楼" )
          ||
          (globalEndPoint.value.floor ==="F4"
          && globalStartPoint.value.floor === "F3"
          && globalStartPoint.value.building === "南楼" )
      ){
        console.log("#############################################################")
        floorList = [startFloor,midFloor ,endFloor];
      }
      if(globalStartPoint.value.floor === "F3" && globalEndPoint.value.floor === "F3" && globalStartPoint.value.building !== globalEndPoint.value.building){
        floorList = [startFloor,midFloor,endFloor];

      }
      if(index===-1)index=0;
      let targetFloor = floorList[index];
      index = (index + 1)%floorList.length;

      if(globalStartPoint.value.floor === "F3" && globalEndPoint.value.floor === "F3" && globalStartPoint.value.building !== globalEndPoint.value.building){
        if(index === 2){
          index = 0;
        }
      }



      console.log("切换到楼层：", targetFloor);
      const cachedData = FLOOR_DATA[targetFloor];
      if (cachedData) {
        handleFloorChange({
          floorName: targetFloor,
          geojsonData: cachedData.data
        });

        // ✅ 重新计算路径
        //先注释掉这个方法，handleFloorChange方法中好像已经有重新计算路径的逻辑了，这段代码好像没有必要2025.11.17
        // if (globalStartPoint.value && globalEndPoint.value) {
        //   calculateAndDrawPath(
        //       // {lat: globalStartPoint.value.lat, lng: globalStartPoint.value.lng},
        //       // {lat: globalEndPoint.value.lat, lng: globalEndPoint.value.lng}
        //       globalStartPoint.value,
        //       globalEndPoint.value
        //   );
        //   // adjustMapView(
        //   //     {lat: globalStartPoint.value.lat, lng: globalStartPoint.value.lng},
        //   //     {lat: globalEndPoint.value.lat, lng: globalEndPoint.value.lng}
        //   // );
        // }
        return;
      }
    }

    function getAllStairsPoints(floorGeoJsons) {
      const stairsPoints = [];

      Object.entries(floorGeoJsons).forEach(([floorName, geojsonData]) => {
        const danYuanMian = geojsonData.danYuanMian;
        L.geoJSON(danYuanMian).eachLayer(layer => {
          const feature = layer.feature;
          if (feature.properties.stairsId) {
            const bounds = layer.getBounds();
            const center = bounds.getCenter();

            stairsPoints.push({
              floor: floorName,
              stairsId: feature.properties.stairsId,
              lat: center.lat,
              lng: center.lng
            });
          }
        });
      });

      return stairsPoints;
    }

    function findNearestStair(startPoint, stairsPoints) {
      let nearestStair = null;
      let minDistance = Infinity;

      stairsPoints.forEach(stair => {
        const distance = turf.distance(turf.point([startPoint.lng, startPoint.lat]), turf.point([stair.lng, stair.lat]));
        if (distance < minDistance) {
          minDistance = distance;
          nearestStair = stair;
        }
      });

      return nearestStair;
    }

    function findMatchingStair(endStairsId, targetFloor, stairsPoints) {
      return stairsPoints.find(stair =>
          stair.stairsId === endStairsId && stair.floor === targetFloor
      );
    }
    function planVeryMultiFloorPath(startLatLng, endLatLng, startFloor, endFloor, allFloorData){
      //默认二楼为中转楼层
      const transStairFloor = "F2";
      clearExistingPathsAndStairs();
      const stairsPoints = getAllStairsPoints(allFloorData);
      console.log("楼梯点", stairsPoints);

      //1、先找距离起点最近的楼梯
      const stairsOnStartFloor = stairsPoints.filter(stair => stair.floor === startFloor);
      const startNearestStair = findNearestStair(startLatLng, stairsOnStartFloor);
      console.log("起点最近楼梯", startNearestStair);
      if (!startNearestStair) throw new Error(`未找到距离起点最近的楼梯`);

      //2、再找距离终点最近的楼梯
      const stairsOnEndFloor = stairsPoints.filter(stair => stair.floor === endFloor);
      const endNearestStair = findNearestStair(endLatLng, stairsOnEndFloor);
      console.log("终点最近楼梯", endNearestStair);
      if (!endNearestStair) throw new Error(`未找到距离终点最近的楼梯`);

      //然后在2楼找匹配的楼梯，如果没有则报错
      //匹配起点楼梯
      const startMatchingStair = findMatchingStair(startNearestStair.stairsId,transStairFloor, stairsPoints);
      console.log("起点匹配的楼梯", startMatchingStair);
      if (!startMatchingStair) throw new Error(`未找到匹配的楼梯`);
      //匹配终点楼梯
      const endMatchingStair = findMatchingStair(endNearestStair.stairsId,transStairFloor, stairsPoints);
      console.log("终点匹配的楼梯", endMatchingStair);
      if (!endMatchingStair) throw new Error(`未找到匹配的楼梯`);

      //路径参数初始化
      let totalDistance = 0;
      let totalDuration = 0;
      const currentTips = [];


      if(startFloor === endFloor && startFloor === "F3" ){
        if (currentFloor.value === startFloor || currentFloor.value === endFloor) {
          // 起点到匹配楼梯的路径
          const path1 = calculatePathOnFloor(startFloor, startLatLng, {
            lat: startNearestStair.lat,
            lng: startNearestStair.lng
          });

          if (path1 && path1.length >= 2) {
            drawPath(path1, "blue", startFloor);
            createAndCacheStairMarker(startNearestStair, startFloor, "前往 " + transStairFloor + " 的楼梯");

            //立即调整视角
            adjustMapView(startLatLng, {
              lat: startNearestStair.lat,
              lng: startNearestStair.lng
            });

            const line1 = turf.lineString(path1.map(point => [point[0], point[1]]));
            const length1 = turf.length(line1, {units: 'meters'});
            if (!isNaN(length1)) {
              totalDuration += parseFloat((length1 / 1.4 / 60).toFixed(1));

              // 添加导航提示
              const {tips, totalDistance: segmentDistance} = generateNavigationTips(path1,false,true);
              totalDistance += segmentDistance;
              currentTips.push(...tips);
              currentTips.push({
                type: 'stair',
                text: `到达中途楼梯，去${transStairFloor} 层，并点击下方切换楼层按钮`,
                color: 'red',
                distance: 0
              });
            }
          }
          // } else if (currentFloor.value === endFloor) {
          // 终点楼梯到终点的路径
          const path2 = calculatePathOnFloor(endFloor, {
            lat: endNearestStair.lat,
            lng: endNearestStair.lng
          }, endLatLng);

          if (path2 && path2.length >= 2) {
            drawPath(path2, "blue", endFloor);
            createAndCacheStairMarker(endNearestStair, endFloor, "来自 " + transStairFloor + " 的楼梯");

            // 立即调整视角
            adjustMapView({
              lat: endNearestStair.lat,
              lng: endNearestStair.lng
            },endLatLng);

            const line2 = turf.lineString(path2.map(point => [point[0], point[1]]));
            const length2 = turf.length(line2, {units: 'meters'});
            if (!isNaN(length2)) {
              totalDuration += parseFloat((length2 / 1.4 / 60).toFixed(1));

              // 添加导航提示
              currentTips.push({
                type: 'stair',
                text: `从 ${startFloor} 层楼梯去`,
                distance: 0
              });
              const {tips, totalDistance: segmentDistance} = generateNavigationTips(path2,true,false);
              currentTips.push(...tips);
              totalDistance += segmentDistance;
            }
          }
        }else if(currentFloor.value === transStairFloor){
          const path3 = calculatePathOnFloor(transStairFloor,
              {lat: startMatchingStair.lat, lng: startMatchingStair.lng},
              {lat: endMatchingStair.lat, lng: endMatchingStair.lng}
          );
          console.log("路线3",path3);

          if (path3 && path3.length >= 2) {
            drawPath(path3, "blue", transStairFloor);
            // 创建起点楼层楼梯标记
            createAndCacheStairMarker(startMatchingStair, transStairFloor, "来自 " + startFloor + " 的楼梯");
            // 创建终点楼层楼梯标记
            createAndCacheStairMarker(endMatchingStair, transStairFloor, "前往 " + endFloor + " 的楼梯");

            // 调整视角
            adjustMapView({
              lat: startMatchingStair.lat,
              lng: startMatchingStair.lng
            }, {
              lat: endMatchingStair.lat,
              lng: endMatchingStair.lng
            });

            const line3 = turf.lineString(path3.map(point => [point[0], point[1]]));
            const length3 = turf.length(line3, {units: 'meters'});
            if (!isNaN(length3)) {
              totalDuration += parseFloat((length3 / 1.4 / 60).toFixed(1));

              // 添加导航提示
              currentTips.push({
                type: 'stair',
                text: `到达中转楼层 ${transStairFloor}，前往通往${endFloor}的楼梯`,
                color: 'red',
                distance: 0
              });

              const {tips, totalDistance: segmentDistance} = generateNavigationTips(path3,true,true);
              currentTips.push(...tips);
              totalDistance += segmentDistance;

              currentTips.push({
                type: 'stair',
                text: `到达通往${endFloor}的楼梯`,
                color: 'red',
                distance: 0
              });
            }
          }
        }
      }else{
        if (currentFloor.value === startFloor ) {
          // 起点到匹配楼梯的路径
          const path1 = calculatePathOnFloor(startFloor, startLatLng, {
            lat: startNearestStair.lat,
            lng: startNearestStair.lng
          });

          if (path1 && path1.length >= 2) {
            drawPath(path1, "blue", startFloor);
            createAndCacheStairMarker(startNearestStair, startFloor, "前往 " + transStairFloor + " 的楼梯");

            //立即调整视角
            adjustMapView(startLatLng, {
              lat: startNearestStair.lat,
              lng: startNearestStair.lng
            });

            const line1 = turf.lineString(path1.map(point => [point[0], point[1]]));
            const length1 = turf.length(line1, {units: 'meters'});
            if (!isNaN(length1)) {
              totalDuration += parseFloat((length1 / 1.4 / 60).toFixed(1));

              // 添加导航提示
              const {tips, totalDistance: segmentDistance} = generateNavigationTips(path1,false,true);
              totalDistance += segmentDistance;
              currentTips.push(...tips);
              currentTips.push({
                type: 'stair',
                text: `到达中途楼梯，去${transStairFloor} 层，并点击下方切换楼层按钮`,
                color: 'red',
                distance: 0
              });
            }
          }
          } else if (currentFloor.value === endFloor) {
          // 终点楼梯到终点的路径
          const path2 = calculatePathOnFloor(endFloor, {
            lat: endNearestStair.lat,
            lng: endNearestStair.lng
          }, endLatLng);

          if (path2 && path2.length >= 2) {
            drawPath(path2, "blue", endFloor);
            createAndCacheStairMarker(endNearestStair, endFloor, "来自 " + transStairFloor + " 的楼梯");

            // 立即调整视角
            adjustMapView({
              lat: endNearestStair.lat,
              lng: endNearestStair.lng
            },endLatLng);

            const line2 = turf.lineString(path2.map(point => [point[0], point[1]]));
            const length2 = turf.length(line2, {units: 'meters'});
            if (!isNaN(length2)) {
              totalDuration += parseFloat((length2 / 1.4 / 60).toFixed(1));

              // 添加导航提示
              currentTips.push({
                type: 'stair',
                text: `从 ${startFloor} 层楼梯去`,
                distance: 0
              });
              const {tips, totalDistance: segmentDistance} = generateNavigationTips(path2,true,false);
              currentTips.push(...tips);
              totalDistance += segmentDistance;
            }
          }
        }else if(currentFloor.value === transStairFloor){
          const path3 = calculatePathOnFloor(transStairFloor,
              {lat: startMatchingStair.lat, lng: startMatchingStair.lng},
              {lat: endMatchingStair.lat, lng: endMatchingStair.lng}
          );
          console.log("路线3",path3);

          if (path3 && path3.length >= 2) {
            drawPath(path3, "blue", transStairFloor);
            // 创建起点楼层楼梯标记
            createAndCacheStairMarker(startMatchingStair, transStairFloor, "来自 " + startFloor + " 的楼梯");
            // 创建终点楼层楼梯标记
            createAndCacheStairMarker(endMatchingStair, transStairFloor, "前往 " + endFloor + " 的楼梯");

            // 调整视角
            adjustMapView({
              lat: startMatchingStair.lat,
              lng: startMatchingStair.lng
            }, {
              lat: endMatchingStair.lat,
              lng: endMatchingStair.lng
            });

            const line3 = turf.lineString(path3.map(point => [point[0], point[1]]));
            const length3 = turf.length(line3, {units: 'meters'});
            if (!isNaN(length3)) {
              totalDuration += parseFloat((length3 / 1.4 / 60).toFixed(1));

              // 添加导航提示
              currentTips.push({
                type: 'stair',
                text: `到达中转楼层 ${transStairFloor}，前往通往${endFloor}的楼梯`,
                color: 'red',
                distance: 0
              });

              const {tips, totalDistance: segmentDistance} = generateNavigationTips(path3,true,true);
              currentTips.push(...tips);
              totalDistance += segmentDistance;

              currentTips.push({
                type: 'stair',
                text: `到达通往${endFloor}的楼梯`,
                color: 'red',
                distance: 0
              });
            }
          }
        }
      }
      //处理起点终点楼层路径规划
      // 更新总距离和时间
      pathDistance.value = isNaN(totalDistance) ? 0 : totalDistance;
      // 推荐路线和同层优先的时间计算都用 pathDuration.value
      // 只需在赋值时用 Math.ceil 取整
      // 推荐路线
      pathDuration.value = isNaN(totalDuration) ? 0 : Math.ceil(totalDuration);

      // 生成导航提示
      pathTips.value = currentTips.length > 0 ? currentTips : generateCrossFloorTips(
          currentFloor.value,
          startFloor,
          endFloor,
          startMatchingStair,
          endNearestStair
      );
    }
    function planMultiFloorPath(startLatLng, endLatLng, startFloor, endFloor, allFloorData, isReverse) {
      if(isReverse){
        try {
          // 特判：起点和终点位置相同
          // if (startLatLng.lat === endLatLng.lat && startLatLng.lng === endLatLng.lng) {
          //   pathDistance.value = 0;
          //   pathDuration.value = 0;
          //   return;
          // }


          clearExistingPathsAndStairs();
          const stairsPoints = getAllStairsPoints(allFloorData);

          // 获取起点楼层和终点楼层的所有楼梯
          let stairsOnStartFloor = stairsPoints.filter(stair => stair.floor === startFloor);
          let stairsOnEndFloor = stairsPoints.filter(stair => stair.floor === endFloor);


          // 对三楼做特殊处理：只遍历相同楼幢的楼梯
          if (startFloor === "F3" && globalStartPoint.value && globalStartPoint.value.building) {
            const startBuilding = globalStartPoint.value.building;
            stairsOnStartFloor = stairsOnStartFloor.filter(stair => {
              // 通过查找GeoJSON数据确定楼梯所属的楼幢
              const stairFeature = findStairFeatureByStairsId(stair.stairsId, startFloor, allFloorData);
              return stairFeature && stairFeature.properties.building === startBuilding && stair.floor === startFloor;
            });

          }

          if (endFloor === "F3" && globalEndPoint.value && globalEndPoint.value.building) {
            const endBuilding = globalEndPoint.value.building;
            stairsOnEndFloor = stairsOnEndFloor.filter(stair => {
              // 通过查找GeoJSON数据确定楼梯所属的楼幢
              const stairFeature = findStairFeatureByStairsId(stair.stairsId, endFloor, allFloorData);
              return stairFeature && stairFeature.properties.building === endBuilding && stair.floor === endFloor;
            });
          }





          if (stairsOnStartFloor.length === 0 || stairsOnEndFloor.length === 0) {
            throw new Error(`起点或终点楼层缺少楼梯信息`);
          }

          // 全局变量存储最优路径信息
          let shortestTotalDistance = Infinity;
          let bestStartStair = null;
          let bestEndStair = null;

          // 遍历所有可能的楼梯组合
          for (const startStair of stairsOnStartFloor) {
            // 在终点楼层找到匹配的楼梯
            const matchingEndStair = findMatchingStair(startStair.stairsId, endFloor, stairsPoints);
            if (!matchingEndStair) {
              console.log("-------------------------------------------------------------------")
              continue;
            }

            // 计算当前组合的总距离
            let currentTotalDistance = 0;

            // 计算起点到起点楼层楼梯的距离
            const path1 = calculatePathOnFloor(startFloor, {
              lat: startStair.lat,
              lng: startStair.lng
            },startLatLng);

            if (path1 && path1.length >= 2) {
              const line1 = turf.lineString(path1.map(point => [point[0], point[1]]));
              const length1 = turf.length(line1, {units: 'meters'});
              if (!isNaN(length1)) {
                currentTotalDistance += length1;
              }
              console.log("第一段路径为",length1)
            }

            // 计算终点楼层楼梯到终点的距离
            const path2 = calculatePathOnFloor(endFloor, endLatLng,{
              lat: matchingEndStair.lat,
              lng: matchingEndStair.lng
            });

            if (path2 && path2.length >= 2) {
              const line2 = turf.lineString(path2.map(point => [point[0], point[1]]));
              const length2 = turf.length(line2, {units: 'meters'});
              if (!isNaN(length2)) {
                currentTotalDistance += length2;
              }
              console.log("第二段路径为",length2)
            }



            // 如果当前路径更短，更新最优路径
            if (currentTotalDistance < shortestTotalDistance && path1 && path2) {
              shortestTotalDistance = currentTotalDistance;
              bestStartStair = startStair;
              bestEndStair = matchingEndStair;
              console.log(currentTotalDistance)
            }
          }

          // 如果没有找到有效的路径组合
          if (!bestStartStair || !bestEndStair) {
            throw new Error(`未找到有效的跨楼层路径`);
          }

          // 使用最优路径进行绘制和导航提示生成
          let totalDistance = 0;
          let totalDuration = 0;
          const currentTips = [];

          // 处理当前楼层的路径
          if (currentFloor.value === startFloor) {
            // 起点到匹配楼梯的路径

            const path1 = calculatePathOnFloor(startFloor,  {
              lat: bestStartStair.lat,
              lng: bestStartStair.lng
            },startLatLng);

            if (path1 && path1.length >= 2) {
              drawPath(path1, "blue", startFloor);
              createAndCacheStairMarker(bestStartStair, startFloor, "前往 " + endFloor + " 的楼梯");

              //立即调整视角
              adjustMapView(startLatLng, {
                lat: bestStartStair.lat,
                lng: bestStartStair.lng
              });

              const line1 = turf.lineString(path1.map(point => [point[0], point[1]]));
              const length1 = turf.length(line1, {units: 'meters'});
              if (!isNaN(length1)) {
                totalDuration += parseFloat((length1 / 1.4 / 60).toFixed(1));

                // 添加导航提示
                currentTips.push({
                  type: 'stair',
                  text: `从 ${startFloor} 层楼梯出去`,
                  color: 'red',
                  distance: 0
                });
                const {tips, totalDistance: segmentDistance} = generateNavigationTips(path1, true, false);
                totalDistance += segmentDistance;
                currentTips.push(...tips);

              }
            }
          } else if (currentFloor.value === endFloor) {

            // 终点楼梯到终点的路径
            // console.log("终点楼梯到终点的路径--------------------------");
            const path2 = calculatePathOnFloor(endFloor, endLatLng,{
              lat: bestEndStair.lat,
              lng: bestEndStair.lng
            });
            // console.log("路径计算成功--------------------------------");
            if (path2 && path2.length >= 2) {
              drawPath(path2, "blue", endFloor);
              // console.log("路线绘制成功--------------------------------");
              createAndCacheStairMarker(bestEndStair, endFloor, "来自 " + startFloor + " 的楼梯");
              // console.log("缓存楼梯创建成功----------------------------------------")
              // 立即调整视角
              adjustMapView({
                lat: bestEndStair.lat,
                lng: bestEndStair.lng
              }, endLatLng);
              // console.log("视角调节成功--------------------");
              const line2 = turf.lineString(path2.map(point => [point[0], point[1]]));
              const length2 = turf.length(line2, {units: 'meters'});
              if (!isNaN(length2)) {
                totalDuration += parseFloat((length2 / 1.4 / 60).toFixed(1));

                // 添加导航提示

                // console.log("即将生成导航指引");
                const {tips, totalDistance: segmentDistance} = generateNavigationTips(path2, false, true);
                currentTips.push(...tips);
                currentTips.push({
                  type: 'stair',
                  text: `到达中途楼梯，去${startFloor} 层，并点击下方切换楼层按钮`,
                  color: 'red',
                  distance: 0
                });
                totalDistance += segmentDistance;
              }
            }
          }

          // 更新总距离和时间
          pathDistance.value = isNaN(totalDistance) ? 0 : totalDistance;
          // 推荐路线和同层优先的时间计算都用 pathDuration.value
          // 只需在赋值时用 Math.ceil 取整
          // 推荐路线
          pathDuration.value = isNaN(totalDuration) ? 0 : Math.ceil(totalDuration);

          // 生成导航提示
          pathTips.value = currentTips.length > 0 ? currentTips : generateCrossFloorTips(
              currentFloor.value,
              startFloor,
              endFloor,
              bestStartStair,
              bestEndStair
          );
        } catch (error) {
          console.error("[跨楼层路径规划失败]", error.message || error);
          pathDistance.value = 0;
          pathDuration.value = 0;
        }
      }else{
        try {
          // 特判：起点和终点位置相同
          // if (startLatLng.lat === endLatLng.lat && startLatLng.lng === endLatLng.lng) {
          //   pathDistance.value = 0;
          //   pathDuration.value = 0;
          //   return;
          // }


          clearExistingPathsAndStairs();
          const stairsPoints = getAllStairsPoints(allFloorData);

          // 获取起点楼层和终点楼层的所有楼梯
          let stairsOnStartFloor = stairsPoints.filter(stair => stair.floor === startFloor);
          let stairsOnEndFloor = stairsPoints.filter(stair => stair.floor === endFloor);


          // 对三楼做特殊处理：只遍历相同楼幢的楼梯
          if (startFloor === "F3" && globalStartPoint.value && globalStartPoint.value.building) {
            const startBuilding = globalStartPoint.value.building;
            stairsOnStartFloor = stairsOnStartFloor.filter(stair => {
              // 通过查找GeoJSON数据确定楼梯所属的楼幢
              const stairFeature = findStairFeatureByStairsId(stair.stairsId, startFloor, allFloorData);
              return stairFeature && stairFeature.properties.building === startBuilding && stair.floor === startFloor;
            });

          }

          if (endFloor === "F3" && globalEndPoint.value && globalEndPoint.value.building) {
            const endBuilding = globalEndPoint.value.building;
            stairsOnEndFloor = stairsOnEndFloor.filter(stair => {
              // 通过查找GeoJSON数据确定楼梯所属的楼幢
              const stairFeature = findStairFeatureByStairsId(stair.stairsId, endFloor, allFloorData);
              return stairFeature && stairFeature.properties.building === endBuilding && stair.floor === endFloor;
            });
          }





          if (stairsOnStartFloor.length === 0 || stairsOnEndFloor.length === 0) {
            throw new Error(`起点或终点楼层缺少楼梯信息`);
          }

          // 全局变量存储最优路径信息
          let shortestTotalDistance = Infinity;
          let bestStartStair = null;
          let bestEndStair = null;

          // 遍历所有可能的楼梯组合
          for (const startStair of stairsOnStartFloor) {
            // 在终点楼层找到匹配的楼梯
            const matchingEndStair = findMatchingStair(startStair.stairsId, endFloor, stairsPoints);
            if (!matchingEndStair) {
              console.log("-------------------------------------------------------------------")
              continue;
            }

            // 计算当前组合的总距离
            let currentTotalDistance = 0;

            // 计算起点到起点楼层楼梯的距离
            const path1 = calculatePathOnFloor(startFloor, startLatLng, {
              lat: startStair.lat,
              lng: startStair.lng
            });

            if (path1 && path1.length >= 2) {
              const line1 = turf.lineString(path1.map(point => [point[0], point[1]]));
              const length1 = turf.length(line1, {units: 'meters'});
              if (!isNaN(length1)) {
                currentTotalDistance += length1;
              }
              console.log("第一段路径为",length1)
            }

            // 计算终点楼层楼梯到终点的距离
            const path2 = calculatePathOnFloor(endFloor, {
              lat: matchingEndStair.lat,
              lng: matchingEndStair.lng
            }, endLatLng);

            if (path2 && path2.length >= 2) {
              const line2 = turf.lineString(path2.map(point => [point[0], point[1]]));
              const length2 = turf.length(line2, {units: 'meters'});
              if (!isNaN(length2)) {
                currentTotalDistance += length2;
              }
              console.log("第二段路径为",length2)
            }



            // 如果当前路径更短，更新最优路径
            if (currentTotalDistance < shortestTotalDistance && path1 && path2) {
              shortestTotalDistance = currentTotalDistance;
              bestStartStair = startStair;
              bestEndStair = matchingEndStair;
              console.log(currentTotalDistance)
            }
          }

          // 如果没有找到有效的路径组合
          if (!bestStartStair || !bestEndStair) {
            throw new Error(`未找到有效的跨楼层路径`);
          }

          // 使用最优路径进行绘制和导航提示生成
          let totalDistance = 0;
          let totalDuration = 0;
          const currentTips = [];

          // 处理当前楼层的路径
          if (currentFloor.value === startFloor) {
            // 起点到匹配楼梯的路径

            const path1 = calculatePathOnFloor(startFloor, startLatLng, {
              lat: bestStartStair.lat,
              lng: bestStartStair.lng
            });

            if (path1 && path1.length >= 2) {
              drawPath(path1, "blue", startFloor);
              createAndCacheStairMarker(bestStartStair, startFloor, "前往 " + endFloor + " 的楼梯");

              //立即调整视角
              adjustMapView(startLatLng, {
                lat: bestStartStair.lat,
                lng: bestStartStair.lng
              });

              const line1 = turf.lineString(path1.map(point => [point[0], point[1]]));
              const length1 = turf.length(line1, {units: 'meters'});
              if (!isNaN(length1)) {
                totalDuration += parseFloat((length1 / 1.4 / 60).toFixed(1));

                // 添加导航提示
                const {tips, totalDistance: segmentDistance} = generateNavigationTips(path1, false, true);
                totalDistance += segmentDistance;
                currentTips.push(...tips);
                currentTips.push({
                  type: 'stair',
                  text: `到达中途楼梯，去${endFloor} 层，并点击下方切换楼层按钮`,
                  color: 'red',
                  distance: 0
                });
              }
            }
          } else if (currentFloor.value === endFloor) {

            // 终点楼梯到终点的路径
            // console.log("终点楼梯到终点的路径--------------------------");
            const path2 = calculatePathOnFloor(endFloor, {
              lat: bestEndStair.lat,
              lng: bestEndStair.lng
            }, endLatLng);
            // console.log("路径计算成功--------------------------------");
            if (path2 && path2.length >= 2) {
              drawPath(path2, "blue", endFloor);
              // console.log("路线绘制成功--------------------------------");
              createAndCacheStairMarker(bestEndStair, endFloor, "来自 " + startFloor + " 的楼梯");
              // console.log("缓存楼梯创建成功----------------------------------------")
              // 立即调整视角
              adjustMapView({
                lat: bestEndStair.lat,
                lng: bestEndStair.lng
              }, endLatLng);
              // console.log("视角调节成功--------------------");
              const line2 = turf.lineString(path2.map(point => [point[0], point[1]]));
              const length2 = turf.length(line2, {units: 'meters'});
              if (!isNaN(length2)) {
                totalDuration += parseFloat((length2 / 1.4 / 60).toFixed(1));

                // 添加导航提示
                currentTips.push({
                  type: 'stair',
                  text: `从 ${endFloor} 层楼梯出去`,
                  distance: 0
                });
                // console.log("即将生成导航指引");
                const {tips, totalDistance: segmentDistance} = generateNavigationTips(path2, true, false);
                currentTips.push(...tips);
                totalDistance += segmentDistance;
              }
            }
          }

          // 更新总距离和时间
          pathDistance.value = isNaN(totalDistance) ? 0 : totalDistance;
          // 推荐路线和同层优先的时间计算都用 pathDuration.value
          // 只需在赋值时用 Math.ceil 取整
          // 推荐路线
          pathDuration.value = isNaN(totalDuration) ? 0 : Math.ceil(totalDuration);

          // 生成导航提示
          pathTips.value = currentTips.length > 0 ? currentTips : generateCrossFloorTips(
              currentFloor.value,
              startFloor,
              endFloor,
              bestStartStair,
              bestEndStair
          );
        } catch (error) {
          console.error("[跨楼层路径规划失败]", error.message || error);
          pathDistance.value = 0;
          pathDuration.value = 0;
        }
      }

    }

    function findStairFeatureByStairsId(stairsId, floor, allFloorData) {
      const floorData = allFloorData[floor];
      if (!floorData || !floorData.danYuanMian) return null;

      let foundFeature = null;
      L.geoJSON(floorData.danYuanMian).eachLayer(layer => {
        const feature = layer.feature;
        if (feature.properties.stairsId === stairsId) {
          foundFeature = feature;
        }
      });

      return foundFeature;
    }

    function calculatePathOnFloor(floorName, startLatLng, endLatLng) {
      const geojsonData = allFloorData.value[floorName]?.routeLine;
      if (!geojsonData) {
        console.error(`未找到楼层 ${floorName} 的路线数据`);
        return null;
      }

      const pathFinder = new GeoJsonPathFinder(geojsonData);
      const points = turf.explode(geojsonData);
      const start = turf.point([startLatLng.lng, startLatLng.lat]);
      const finish = turf.point([endLatLng.lng, endLatLng.lat]);

      const startInNetwork = turf.nearestPoint(start, points);
      const endInNetwork = turf.nearestPoint(finish, points);

      const newPath = pathFinder.findPath(startInNetwork, endInNetwork);
      return newPath ? newPath.path : null;
    }

    function drawPath(pathCoords, color, floorName) {
      if (!pathCoords || !pathCoords.length) return;

      const leafletCoords = toLeafletCoords(pathCoords);

      // 路线外边框，使其更突出
      const outline = L.polyline(leafletCoords, {
        color: 'rgba(66, 133, 244, 0.3)', // 半透明、更宽的蓝色外框
        weight: 9,
        lineCap: 'round',
        lineJoin: 'round',
      }).addTo(map.value);

      // 主要的动态路线
      const line = L.polyline(leafletCoords, {
        color: '#4285F4', // 使用更专业的蓝色
        weight: 5,
        className: 'animated-path', // 添加此类以应用动画
        lineCap: 'round',
        lineJoin: 'round',
      }).addTo(map.value);

      // 缓存路径图层
      if (!allFloorData.value[floorName]) {
        allFloorData.value[floorName] = {};
      }
      allFloorData.value[floorName].pathLayer = {outline, line}; // 保存两个图层
    }

    async function clearPointsAndMarkers() {
      // 清除路径
      if (drawnPath.value) {
        if (drawnPath.value.outline && map.value.hasLayer(drawnPath.value.outline)) {
          map.value.removeLayer(drawnPath.value.outline);
        }
        if (drawnPath.value.line && map.value.hasLayer(drawnPath.value.line)) {
          map.value.removeLayer(drawnPath.value.line);
        }
        drawnPath.value = null;
      }

      // 清除终点状态
      globalEndPoint.value = null;
      endPointData.value = {roomName: '', floor: null};

      // 更新UI状态
      showTopDrawer.value = false;
      showTipMessageDrawer.value = false;

      // ✅ 新增：清除所有路径和楼梯标记（包括其他楼层）
      clearExistingPathsAndStairs();

      // 刷新地图标记
      updateMarkersOnMap();

      //根据id获取楼层
      const response = await get_floor(id)
      const floor = response.data
      handleFloorChange({
        floorName: floor,
        geojsonData: FLOOR_DATA[floor].data
      });

    }


    function updateMarkersOnMap() {
      // 清除现有标记
      if (startMarker.value) {
        map.value.removeLayer(startMarker.value);
        startMarker.value = null;
      }

      if (endMarker.value) {
        map.value.removeLayer(endMarker.value);
        endMarker.value = null;
      }

      // 添加起点标记
      if (globalStartPoint.value && globalStartPoint.value.floor === currentFloor.value) {
        const startIcon = L.icon({
          iconUrl: "img/start.png",
          iconSize: [32, 32],
          iconAnchor: [16, 32]
        });

        startMarker.value = L.marker(
            [globalStartPoint.value.lat, globalStartPoint.value.lng],
            {icon: startIcon, draggable: false}
        ).addTo(map.value);
      }

      // 添加终点标记
      if (globalEndPoint.value && globalEndPoint.value.floor === currentFloor.value) {
        const endIcon = L.icon({
          iconUrl: "img/end.png",
          iconSize: [32, 32],
          iconAnchor: [16, 32]
        });

        endMarker.value = L.marker(
            [globalEndPoint.value.lat, globalEndPoint.value.lng],
            {icon: endIcon, draggable: false}
        ).addTo(map.value);
      }

      // ✅ 在更新标记时，同步刷新所有标签的位置
      labelData.value.forEach(({marker, center}) => {
        if (center && marker) {
          marker.setLatLng(center); // 强制更新标记位置
        }
      });

      // 重新绘制路径
      if (globalStartPoint.value && globalEndPoint.value) {
        calculateAndDrawPath(
            // {lat: globalStartPoint.value.lat, lng: globalStartPoint.value.lng},
            // {lat: globalEndPoint.value.lat, lng: globalEndPoint.value.lng}
            globalStartPoint.value,
            globalEndPoint.value
        );
      }
    }


    function handleFloorChange({floorName, geojsonData}) {
      // 检查地图是否已初始化
      if (!map.value) {
        console.warn('地图对象未初始化');
        return;
      }
      // 如果点击的是当前楼层，直接返回，避免重复操作
      if (currentFloor.value === floorName) {
        return;
      }
      clearMarkers();
      currentFloor.value = floorName;
      allFloorData.value[floorName] = geojsonData;
      // 同步FloorSwitch高亮
      if (floorSwitchRef.value && floorSwitchRef.value.syncCurrentFloor) {
        floorSwitchRef.value.syncCurrentFloor(floorName);
      }

      // 清除旧路径和标记
      if (drawnPath.value) {
        if (drawnPath.value.outline && map.value.hasLayer(drawnPath.value.outline)) {
          map.value.removeLayer(drawnPath.value.outline);
        }
        if (drawnPath.value.line && map.value.hasLayer(drawnPath.value.line)) {
          map.value.removeLayer(drawnPath.value.line);
        }
        drawnPath.value = null;
      }
      if (stairMarker1.value) {
        map.value.removeLayer(stairMarker1.value);
        stairMarker1.value = null;
      }
      if (stairMarker2.value) {
        map.value.removeLayer(stairMarker2.value);
        stairMarker2.value = null;
      }

      // 清除所有旧图层和标签

      Object.values(layers).forEach(layer => {
        if (layer && map.value.hasLayer(layer)) {
          map.value.removeLayer(layer);
        }
      });
      labelData.value.forEach(({marker}) => {
        if (map.value.hasLayer(marker)) {
          map.value.removeLayer(marker);
        }
      });
      labelData.value = [];
      // 添加新图层
      layers.waiKuangMian = L.geoJSON(geojsonData.waiKuangMian, {
        style(feature) {
          return {
            fillColor: "#ffffff",
            color: feature.properties.stroke || "#000000",
            weight: feature.properties["stroke-width"] || 1,
            fillOpacity: feature.properties["fill-opacity"] || 1,
            stroke: false
          };
        }
      }).addTo(map.value);

      layers.danYuanMian = L.geoJSON(geojsonData.danYuanMian, {

        style(feature) {
          return {
            fillColor: feature.properties.fill || "#feebcd",
            color: feature.properties.stroke || "#919191",
            // weight: feature.properties["stroke-width"] || 1,
            weight: (feature.properties.name && feature.properties.nickname.includes('#')) ? 0 : 1,
            fillOpacity: feature.properties["fill-opacity"] || 0.8
          };
        },

        onEachFeature(feature, layer) {

          // layer.on("click", function () {
          //   // showQuickEntryDrawer.value = false; // 删除这行
          //   showNavigationDrawer.value = true;
          //   showTipMessageDrawer.value = false;
          //   updateRoomInfo(feature.properties.name || '', feature.properties.id || '');
          // });


          if (feature.geometry.type === "Polygon" || feature.geometry.type === "MultiPolygon") {
            const center = getFeatureCenter(feature);//获取面中心点
            if (center && feature.properties.name) {
              const name = feature.properties.name;
              const isWC = name.includes('WC');
              const isStair = name.includes('楼梯');
              const isBigDoor = (name === '东侧出入口' || name === '北楼北侧出入口' || name === '南楼西侧出入口');
              // 新增判断：是否包含"出入口"但不是已特判的三个出入口
              const isOtherDoor = name.includes('出入口') && !isBigDoor;

              // 特判停车场出入口，设置不同的图标
              let isParkingExit = false;
              let isParkingEntrance = false;
              if (name === '行政中心东侧地下停车场出口' || name === '行政中心东南侧地下停车场出口') {
                isParkingExit = true;
              } else if (name === '行政中心南侧地下停车场入口' || name === '行政中心西南侧地下停车场入口' || name === '行政中心西侧地下停车场入口') {
                isParkingEntrance = true;
              }

              const doorNum = feature.properties.doorNum;
              // 检查是否有nickname属性
              const nickname = feature.properties.nickname;
              // 初始zoom
              const zoom = map.value && map.value.getZoom ? map.value.getZoom() : 20;
              const fontSize = Math.max(12, Math.min(zoom * 2, 32));
              const iconWidth = Math.max(60, fontSize * 4);
              const iconHeight = fontSize + 8;
              const marker = L.marker(center, {
                icon: L.divIcon({
                  className: "label-class",
                  html: isStair
                      ? `<div style=\"background:#fff;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:24px;height:24px;display:flex;align-items:center;justify-content:center;border:2px solid #4285F4;\"><img src=\"img/stair1.png\" style=\"width:14px;height:14px;display:block;\" /></div>`
                      : isBigDoor
                          ? `<div style=\"background:#fff;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:24px;height:24px;display:flex;align-items:center;justify-content:center;border:2px solid #4285F4;\"><img src=\"img/indoor.png\" style=\"width:14px;height:14px;display:block;\" /></div>`
                          : isOtherDoor  // 添加对其他出入口的处理
                              ? `<div style=\"background:#fff;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:24px;height:24px;display:flex;align-items:center;justify-content:center;border:2px solid #4285F4;\"><img src=\"img/indoor.png\" style=\"width:14px;height:14px;display:block;\" /></div>`
                              : isWC
                                  ? `<div style=\"background:#fff;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:24px;height:24px;display:flex;align-items:center;justify-content:center;border:2px solid #43b244;\"><img src=\"img/WC.png\" style=\"width:14px;height:14px;display:block;\" /></div>`
                                  : isParkingExit
                                      ? `<div style=\"background:#fff;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:30px;height:30px;display:flex;align-items:center;justify-content:center;border:2px solid #4285F4;\"><img :src="parkingLotOut" style=\"width:22px;height:22px;display:block;\" /></div>`
                                      : isParkingEntrance
                                          ? `<div style=\"background:#fff;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:30px;height:30px;display:flex;align-items:center;justify-content:center;border:2px solid #4285F4;\"><img :src="parkingLotIn" style=\"width:22px;height:22px;display:block;\" /></div>`
                                      : (nickname || name), // 如果有nickname则优先显示nickname
                  iconSize: isStair || isBigDoor || isOtherDoor || isWC || isParkingExit || isParkingEntrance ? [30, 30] : [iconWidth, iconHeight],
                  iconAnchor: isStair || isBigDoor || isOtherDoor || isWC || isParkingExit || isParkingEntrance ? [15, 15] : [iconWidth / 2, iconHeight / 2]
                }),
                interactive: false
              });
              marker.addTo(map.value); // 确保label marker被添加到地图上
              labelData.value.push({marker, center, name, isWC, isStair, isBigDoor, isOtherDoor, doorNum, nickname, isParkingExit, isParkingEntrance});
            }
          }

        }
      }).addTo(map.value);

      layers.routeLine = L.geoJSON(geojsonData.routeLine, {
        style(feature) {
          return {
            color: feature.properties.stroke || "#919191",
            weight: feature.properties["stroke-width"] || 1,
            opacity: feature.properties["stroke-opacity"] || 0.8
          };
        }
      })

      // if (id.value && floorName === "F1") {
      //   setRoomById(id.value)
      // }
      if (id.value) {
        setRoomById(id.value)
      }
      pathFinder.value = new GeoJsonPathFinder(geojsonData.routeLine);//创建路径查找对象

      // 更新标记显示
      updateMarkersOnMap();
      adjustMapViewForFloor(floorName);
      handleZoomChange(); // 在每次楼层切换后调用，确保标签状态正确
      // 如果正在进行跨楼层导航，重新计算当前楼层应显示的路径部分
      if (globalStartPoint.value && globalEndPoint.value &&
          globalStartPoint.value.floor !== globalEndPoint.value.floor) {
        calculateAndDrawPath(
            // {lat: globalStartPoint.value.lat, lng: globalStartPoint.value.lng},
            // {lat: globalEndPoint.value.lat, lng: globalEndPoint.value.lng}
            globalStartPoint.value,
            globalEndPoint.value
        );
      }
      // 自动设置终点
      if (
          pendingTargetId.value &&
          pendingTargetFloor.value &&
          floorName === pendingTargetFloor.value
      ) {
        roomId.value = pendingTargetId.value;
        // setEndPointFromRoom(); // 此时已在终点楼层，可以成功设置终点
        pendingTargetId.value = null;
        pendingTargetFloor.value = null;

        // 在终点设置成功后，立即切换回一楼
        // if (floorName !== 'F1') {
        //   nextTick(() => { // 使用 nextTick 确保状态更新完毕
        //     if (floorSwitchRef.value && floorSwitchRef.value.loadFloorData) {
        //       floorSwitchRef.value.loadFloorData('F1');
        //     } else {
        //
        //       handleFloorChange({
        //         floorName: 'F1',
        //         geojsonData: FLOOR_DATA["F1"].data
        //       });
        //
        //     }
        //   });
        // }
        // 在终点设置成功后，立即切换回起点楼层
        // if (floorName !== startPointData.value.floor) {
        //   nextTick(() => { // 使用 nextTick 确保状态更新完毕
        //     const startFloor = startPointData.value.floor;
        //     if (startFloor && FLOOR_DATA[startFloor]) {
        //       if (floorSwitchRef.value && floorSwitchRef.value.loadFloorData) {
        //         floorSwitchRef.value.loadFloorData(startFloor);
        //       } else {
        //         handleFloorChange({
        //           floorName: startFloor,
        //           geojsonData: FLOOR_DATA[startFloor].data
        //         });
        //       }
        //     }
        //   });
        // }
      }

      // 如果当前楼层不是目标楼层，但有待处理的终点，也尝试设置
      if (pendingTargetId.value && pendingTargetFloor.value && floorName !== pendingTargetFloor.value) {
        // 等待目标楼层加载完成后再设置
        // 这里可以添加一个延迟，确保目标楼层数据已加载
        setTimeout(() => {
          if (pendingTargetId.value && pendingTargetFloor.value) {
            roomId.value = pendingTargetId.value;
            setEndPointFromRoom();
            pendingTargetId.value = null;
            pendingTargetFloor.value = null;
          }
        }, 500);
      }
    }

    // 新增函数：根据楼层调整地图视角
    function adjustMapViewForFloor(floorName) {
      const settings = floorViewSettings[floorName];
      if (settings && map.value) {
        if (settings.center && settings.zoom) {
          map.value.setView(settings.center, settings.zoom, {
            animate: false, // 禁用动画避免延迟
            duration: 0
          });
        }
      } else {
        console.warn(`未找到楼层 ${floorName} 的视角设置`);
      }
    }

    function updateRoomInfo(name, id) {
      roomName.value = name;
      roomId.value = id;
    }

    async function setEndPointFromRoom() {
      endPointData.value = {
        id: route.query.targetId,
        floor: route.query.targetFloor,
      }
      try {
        const targetFloor = endPointData.value.floor;
        if (!targetFloor) {
          console.error("目标楼层未定义");
          return;
        }
        console.log("终点房间名：" , roomName.value)
        // ✅ 如果当前楼层不是目标楼层，先切换
        if (currentFloor.value !== targetFloor) {
          const cachedData = FLOOR_DATA[targetFloor];
          if (!cachedData) {
            console.error(`未找到楼层 ${targetFloor} 数据`);
            return;
          }

          handleFloorChange({
            floorName: targetFloor,
            geojsonData: cachedData.data
          });

          // ✅ 等待 DOM 更新完成
          await nextTick();
        }

        // ✅ 现在可以安全地在目标楼层查找房间
        const danYuanMianLayers = layers.danYuanMian.getLayers();
        const clickedLayer = danYuanMianLayers.find(layer => {
          return String(layer.feature?.properties?.id) === String(roomId.value);
        });

        if (!clickedLayer) {
          console.error("未找到对应房间:", roomName.value);
          return;
        }

        const roomBounds = clickedLayer.getBounds();
        const roomCenter = roomBounds.getCenter();

        const pathGeoJSON = layers.routeLine.toGeoJSON();
        const centerPoint = turf.point([roomCenter.lng, roomCenter.lat]);
        const pathPoints = turf.explode(pathGeoJSON);
        const nearestPoint = turf.nearestPoint(centerPoint, pathPoints);

        if (!nearestPoint?.geometry?.coordinates) {
          console.error("无法找到最近的路径点");
          return;
        }
        console.log("最近路径点：", nearestPoint)

        const [lng, lat] = nearestPoint.geometry.coordinates;

        const roomNameFromLayer = clickedLayer.feature.properties.name || '';
        roomName.value = roomNameFromLayer;

        // 获取建筑名称（假设建筑信息存储在 feature.properties.building 中）
        const building = clickedLayer.feature.properties.building || '未知建筑';

        globalEndPoint.value = {
          lat: Number(lat),
          lng: Number(lng),
          roomName: roomNameFromLayer,
          floor: currentFloor.value,
          doorNum: clickedLayer.feature.properties.doorNum || '',
          building: building,
        };

        endPointData.value = {
          roomName: roomNameFromLayer,
          floor: currentFloor.value,
          building: building,
        };


        updateMarkersOnMap();
        showTipMessageDrawer.value = false;
        showNavigationDrawer.value = true;

        if (globalStartPoint.value && globalEndPoint.value) {
          calculateAndDrawPath(
              // {lat: globalStartPoint.value.lat, lng: globalStartPoint.value.lng},
              // {lat: globalEndPoint.value.lat, lng: globalEndPoint.value.lng}
              globalStartPoint.value,
              globalEndPoint.value
          );
        }

      } catch (error) {
        console.error("设置终点失败:", error);
      }
      switchToTargetFloor();
    }

    function calculateAndDrawPath(startPos, endPos) {
      if (!pathFinder.value) return;
      const startLatLng = {lat: Number(startPos.lat), lng: Number(startPos.lng)};
      const endLatLng = {lat: Number(endPos.lat), lng: Number(endPos.lng)};
      console.log("----------------起点：", startLatLng)
      console.log("----------------终点：", endLatLng)
      // ✅ 新增判断：如果当前楼层不是起点或终点楼层，则不绘制路径
      // if (currentFloor.value !== globalStartPoint.value?.floor &&
      //     currentFloor.value !== globalEndPoint.value?.floor) {
      //   clearExistingPathsAndStairs(); // 清除路径和楼梯标记
      //   return;
      // }
      // 特判：起点和终点位置相同
      if (startLatLng.lat === endLatLng.lat && startLatLng.lng === endLatLng.lng) {
        pathDistance.value = 0;
        pathDuration.value = 0;
        return;
      }

      const startFloor = globalStartPoint.value?.floor;
      const endFloor = globalEndPoint.value?.floor;
      const startBuilding = globalStartPoint.value?.building;
      const endBuilding = globalEndPoint.value?.building;
      // 统一清除现有路径和楼梯标记
      clearExistingPathsAndStairs();

      //同层同楼：同层同楼幢路径规划时可以直接计算路径
      //同层不同楼：起点楼层为一楼或二楼时可以直接计算路径
      if ((startFloor === endFloor&& startBuilding === endBuilding)||((startFloor==="F1"||startFloor==="F2")&&startFloor===endFloor)) {
        const points = turf.explode(layers.routeLine.toGeoJSON());//导入所有点
        const start = turf.point([startLatLng.lng, startLatLng.lat]);
        const finish = turf.point([endLatLng.lng, endLatLng.lat]);
        const startInNetwork = turf.nearestPoint(start, points);
        const endInNetwork = turf.nearestPoint(finish, points);

        // 添加调试语句检查点是否在pathFinder网络上以及是否连通
        console.log("检查 startInNetwork 是否在 pathFinder 网络上:", {
          hasProperties: !!startInNetwork.properties,
          hasNearestPoint: !!startInNetwork.properties?.nearestPoint,
          coordinates: startInNetwork.geometry?.coordinates
        });

        console.log("检查 endInNetwork 是否在 pathFinder 网络上:", {
          hasProperties: !!endInNetwork.properties,
          hasNearestPoint: !!endInNetwork.properties?.nearestPoint,
          coordinates: endInNetwork.geometry?.coordinates
        });

        // 尝试查找从起点到终点的路径以检查连通性
        const connectivityTest = pathFinder.value.findPath(startInNetwork, endInNetwork);
        console.log("startInNetwork 和 endInNetwork 是否连通:", {
          isConnected: !!connectivityTest,
          pathLength: connectivityTest?.path?.length || 0
        });

        const newPath = pathFinder.value.findPath(startInNetwork, endInNetwork);//路径规划

        console.log("----------------", pathFinder.value)
        console.log("startInNetwork:",startInNetwork)
        console.log("endInNetwork:",endInNetwork)

        console.log("----------------路径规划结果：", newPath)

        if (newPath) {
          const pathCoordinates = toLeafletCoords(newPath.path);

          // 路线外边框
          const outline = L.polyline(pathCoordinates, {
            color: 'rgba(66, 133, 244, 0.3)',
            weight: 9,
            lineCap: 'round',
            lineJoin: 'round',
          }).addTo(map.value);

          // 主要的动态路线
          const line = L.polyline(pathCoordinates, {
            color: '#4285F4',
            weight: 5,
            className: 'animated-path',
            lineCap: 'round',
            lineJoin: 'round',
          }).addTo(map.value);

          drawnPath.value = {outline, line};

          // 计算距离和时间
          const lineForDistance = turf.lineString(pathCoordinates.map(([lat, lng]) => [lng, lat]));
          const length = turf.length(lineForDistance, {units: 'meters'});
          // pathDistance.value = length;
          // 同层优先
          pathDuration.value = Math.ceil(length / 1.4 / 60); // 原来

          // 生成导航提示
          // pathTips.value = generateNavigationTips(pathCoordinates);
          const {tips, totalDistance} = generateNavigationTips(pathCoordinates.map(([lat, lng]) => [lng, lat]));
          pathTips.value = tips;
          pathDistance.value = totalDistance; // 使用计算出的总距离更新 pathDistance
          adjustMapView(startLatLng, endLatLng);
        }
      } else if(startBuilding===endBuilding){
        // 不同层同楼路线规划
        planMultiFloorPath(
            startLatLng,
            endLatLng,
            startFloor,
            endFloor,
            allFloorData.value,
            false
        );
      }else if(startFloor==="F1"||startFloor==="F2"){
        //不同层不同楼：起点为F1、F2时，路径规划
        planMultiFloorPath(
            startLatLng,
            endLatLng,
            startFloor,
            endFloor,
            allFloorData.value,
            false
        );
      }else if(endFloor==="F1"||endFloor==="F2"){
        //不同层不同楼：终点为F1、F2时，路径规划
        planMultiFloorPath(
            endLatLng,
            startLatLng,
            endFloor,
            startFloor,
            allFloorData.value,
            true
        )
      } else{
        //不同层不同楼：终点为F3、F4时，路径规划
        planVeryMultiFloorPath(startLatLng, endLatLng,startFloor,endFloor,allFloorData.value)
      }
    }

    function adjustMapView(startLatLng, endLatLng, pathCoordinates = null) {
      // console.log("开始视角调节---------------------")
      const centerLat = (startLatLng.lat + endLatLng.lat) / 2;
      const centerLng = (startLatLng.lng + endLatLng.lng) / 2;
      const center = [centerLat, centerLng];

      // 设置地图视图到中间位置，保持当前缩放级别
      map.value.setView(center, map.value.getZoom(), {animate: true});
      return;
    }

      // map.value.fitBounds(bounds, {
      //   padding: [40, 40],
      //   maxZoom: 20,
      //   animate: true
      // });
    // }

    function toLeafletCoords(coords) {
      return coords.map(([lng, lat]) => [lat, lng]);
    }

    function getFeatureCenter(feature) {
      const coords = feature.geometry.coordinates;
      let latlngs = [];

      if (feature.geometry.type === "Polygon") {
        latlngs = coords[0];
      } else if (feature.geometry.type === "MultiPolygon") {
        latlngs = coords[0][0];
      }

      const latSum = latlngs.reduce((sum, coord) => sum + coord[1], 0);
      const lngSum = latlngs.reduce((sum, coord) => sum + coord[0], 0);
      const lat = latSum / latlngs.length;
      const lng = lngSum / latlngs.length;

      return [lat, lng];
    }

    function onDrawerHeightChange(val) {
      drawerHeight.value = val;
    }

    function clearMarkers() {
      if (startMarker.value) {
        map.value.removeLayer(startMarker.value);
        startMarker.value = null;
      }

      if (endMarker.value) {
        map.value.removeLayer(endMarker.value);
        endMarker.value = null;
      }
    }

    function clearNonCurrentFloorLayers(currentFloorName) {
      Object.keys(allFloorData.value).forEach(floorName => {
        const floorData = allFloorData.value[floorName];

        // 清除路径
        if (floorData.pathLayer) {
          if (floorData.pathLayer.outline && map.value.hasLayer(floorData.pathLayer.outline)) {
            map.value.removeLayer(floorData.pathLayer.outline);
          }
          if (floorData.pathLayer.line && map.value.hasLayer(floorData.pathLayer.line)) {
            map.value.removeLayer(floorData.pathLayer.line);
          }
          floorData.pathLayer = null;
        }

        // 清除楼梯标记
        if (floorData.stairMarkers && Array.isArray(floorData.stairMarkers)) {
          floorData.stairMarkers.forEach(marker => {
            if (map.value.hasLayer(marker)) {
              map.value.removeLayer(marker);
            }
          });
          floorData.stairMarkers = [];
        }
      });
    }

    function createAndCacheStairMarker(stair, floorName, popupText) {
      const stairIcon = L.icon({
        iconUrl: stairIconImage,
        iconSize: [24, 24],
        iconAnchor: [12, 24]
      });

      const marker = L.marker([stair.lat, stair.lng], {icon: stairIcon})
          .bindPopup(popupText)
          .addTo(map.value);

      if (!allFloorData.value[floorName]) {
        allFloorData.value[floorName] = {};
      }

      if (!allFloorData.value[floorName].stairMarkers) {
        allFloorData.value[floorName].stairMarkers = [];
      }

      allFloorData.value[floorName].stairMarkers.push(marker);
    }

    function clearExistingPathsAndStairs() {
      // 清除当前路径
      if (drawnPath.value) {
        if (drawnPath.value.outline && map.value.hasLayer(drawnPath.value.outline)) {
          map.value.removeLayer(drawnPath.value.outline);
        }
        if (drawnPath.value.line && map.value.hasLayer(drawnPath.value.line)) {
          map.value.removeLayer(drawnPath.value.line);
        }
        drawnPath.value = null;
      }

      // 清除所有楼层的路径和楼梯标记
      clearNonCurrentFloorLayers(currentFloor.value);

      // 清除楼梯标记（如果存在）
      if (stairMarker1.value) {
        map.value.removeLayer(stairMarker1.value);
        stairMarker1.value = null;
      }
      if (stairMarker2.value) {
        map.value.removeLayer(stairMarker2.value);
        stairMarker2.value = null;
      }
    }


    const hideFloorSwitch = computed(() => {
      return drawerHeight.value > 350;
    });

    function loadFloorData(floorNumber) {
      const floorStr = String(floorNumber);

      if (!floorStr || !['1', '2', '3', '4'].includes(floorStr)) {
        console.error('无效的楼层号:', floorStr);
        return;
      }

      const floorKey = `F${floorStr}`;
      const cachedData = FLOOR_DATA[floorKey]; // 直接从缓存获取数据

      if (cachedData) {
        // 使用缓存数据触发楼层切换
        handleFloorChange({
          floorName: floorKey, // 使用楼层标识符作为floorName
          geojsonData: cachedData // 直接使用缓存的geojson数据
        });
      } else {
        console.error(`缓存中未找到楼层 ${floorKey} 数据`);
      }
    }


    // setup 函数中定义
    const currentRoomDoorNum = ref(''); // 当前房间名称

// 在 setRoomById 函数中更新 currentRoomDoorNum
    function setRoomById(id) {
      console.log("setRoomById:", id);
      // ✅ 保留 id 用于全局状态
      currentRoomDoorNum.value = id
      try {
        if (!layers.danYuanMian || !layers.routeLine) {
          console.warn('图层未加载完成，无法定位')
          return
        }

        const danYuanMianLayers = layers.danYuanMian.getLayers();
        let clickedLayer = null;

        for (let i = 0; i < danYuanMianLayers.length; i++) {
          const layer = danYuanMianLayers[i];
          if (String(layer.feature.properties.id) === String(id)) {
            clickedLayer = layer;
            break;
          }
        }

        if (!clickedLayer) {
          console.warn(`未找到 ID 为 ${id} 的房间`)
          return
        }


        //获取房间所在楼幢
        const building = clickedLayer.feature.properties.building || '未知建筑';
        // 获取房间名称
        const roomName = clickedLayer.feature.properties.name || '123';
        currentRoomDoorNum.value = roomName; // 设置当前房间名
        console.log("当前点击的图层:", clickedLayer);
        console.log("房间名称:", roomName);
        console.log("设置 currentRoomDoorNum 为:", roomName);


        // 设置全局起点
        const roomBounds = clickedLayer.getBounds();
        const roomCenter = roomBounds.getCenter();

        const pathGeoJSON = layers.routeLine.toGeoJSON();
        const centerPoint = turf.point([roomCenter.lng, roomCenter.lat]);
        const pathPoints = turf.explode(pathGeoJSON);
        const nearestPoint = turf.nearestPoint(centerPoint, pathPoints);

        if (!nearestPoint?.geometry?.coordinates) {
          console.warn('无法找到最近的路径点')
          return
        }

        const [lng, lat] = nearestPoint.geometry.coordinates;

        globalStartPoint.value = {
          lat: Number(lat),
          lng: Number(lng),
          roomName: roomName,
          floor: currentFloor.value,
          doorNum: clickedLayer.feature.properties.doorNum || '',
          building: building//添加building属性
        };

        startPointData.value = {
          roomName: roomName,
          floor: currentFloor.value,
          building: building
        };
        updateMarkersOnMap();

      } catch (error) {
        console.error("设置起点失败:", error)
      }
    }


    function generateNavigationTips(path,isPathStartInStairs = false ,isPathEndInStairs = false) {
      //path是路线中一系列点的数组
      //isPathStartInStairs是布尔型数据，用于判断起点是否为楼梯
      //isPathEndInStairs是布尔型数据，用于判断终点是否为楼梯
      if (!path || path.length < 2) return [];
      const tips = [];
      let segmentDistance = 0;
      let totalDistance = 0;
      let previousBearing = null;
      let prevPoint = path[0];
      let lastTurnPoint = path[0];//记录上一个转向的节点
      // 计算初始朝向
      if (path.length > 1) {
        previousBearing = turf.bearing(
            turf.point(prevPoint),
            turf.point(path[1])
        );
      }

      for (let i = 1; i < path.length; i++) {
        const currPoint = path[i];
        // const distance = turf.distance(
        //     turf.point(prevPoint),
        //     turf.point(currPoint),
        //     {units: 'meters'}
        // );
        // console.log('距离加了',i,'次');
        // 使用取整后的距离值进行累加
        // const roundedDistance = Math.round(distance);
        // totalDistance += roundedDistance;
        // segmentDistance += roundedDistance;


        const currentBearing = turf.bearing(
            turf.point(prevPoint),
            turf.point(currPoint)
        );

        let angleChange = 0;
        if (previousBearing !== null) {
          angleChange = ((currentBearing - previousBearing + 540) % 360) - 180;
        }

        // 判断是否需要转向
        const needTurn = Math.abs(angleChange) > 30 || i === path.length - 1;

        if (needTurn) {
          const distance = turf.distance(
              turf.point(lastTurnPoint),
              turf.point(prevPoint),
              {units: 'meters'}
          );
          const roundedDistance = Math.round(distance);
          totalDistance += roundedDistance;
          segmentDistance += roundedDistance;
          // 添加直行提示（如果距离足够）
          //起点是楼梯时需要显示导航提示，不是则不显示第一段导航提示
          if (segmentDistance > 1) {
            if(lastTurnPoint!==path[0]||isPathStartInStairs){
              tips.push({
              type: 'straight',
              text: `直行 ${segmentDistance} 米`,
              distance: segmentDistance
            });
            }
          }

          // 添加转向提示
          if (Math.abs(angleChange) > 30&&(lastTurnPoint!==path[0]||isPathStartInStairs)&&(i<path.length-1||isPathEndInStairs)) {
            let turnType = '';
            if (Math.abs(angleChange) > 150) {
              turnType = '掉头';
            } else if (angleChange > 30) {
              turnType = '右转';
            } else if (angleChange < -30) {
              turnType = '左转';
            }

            tips.push({
              type: 'turn',
              text: turnType,
              angle: angleChange,
              distance: 0
            });
          }
          lastTurnPoint = prevPoint;
          segmentDistance = 0;
        }
        previousBearing = currentBearing;
        prevPoint = currPoint;
      }

      // // 添加到达提示
      // tips.push({
      //   type: 'arrival',
      //   text: `到达目的地`,
      //   distance: 0
      // });

      // 只有当路径的最后一个点是终点时才添加到达提示
      if (path.length > 1) {
        const lastPoint = path[path.length - 1];
        const endPoint = globalEndPoint.value;

        // 检查当前路径的最后一个点是否位于终点所在楼层
        if (endPoint && currentFloor.value === endPoint.floor) {
          // 构建到达提示文本，包含房间名和门牌号
          let arrivalText = '到达目的地';
          if (endPoint.roomName && endPoint.doorNum) {
            arrivalText = `到达${endPoint.roomName}（${endPoint.doorNum}室）`;
          } else if (endPoint.roomName) {
            arrivalText = `到达${endPoint.roomName}`;
          } else if (endPoint.doorNum) {
            arrivalText = `到达${endPoint.doorNum}办公室`;
          }

          tips.push({
            type: 'arrival',
            text: arrivalText,
            color: 'red',
            distance: 0
          });
        }
      }
      return {tips, totalDistance};
    }

    function generateCrossFloorTips(currentFloor, startFloor, endFloor, startStair, endStair) {
      const tips = [];

      if (currentFloor === startFloor) {
        tips.push({
          type: 'floor',
          text: `当前在${startFloor}层，请前往${endFloor}层`,
          action: 'switch'
        });
        tips.push({
          type: 'stair',
          text: `去楼梯并前往${endFloor}层`,
          distance: 0
        });
      } else if (currentFloor === endFloor) {
        tips.push({
          type: 'floor',
          text: `当前在${endFloor}层，从${startFloor}层出发`,
          action: 'none'
        });
        tips.push({
          type: 'stair',
          text: `从楼梯出来后继续前进`,
          distance: 0
        });
      } else {
        tips.push({
          type: 'floor',
          text: `请先切换到${startFloor}层或${endFloor}层`,
          action: 'none'
        });
      }

      return tips;
    }

    function handleZoomChange() {
      // 添加地图存在性检查
      if (!map.value) {
        console.warn('地图对象不存在，无法处理缩放变化');
        return;
      }
      try {
        const zoom = map.value.getZoom();
        const maxZoom = map.value.getMaxZoom();

        labelData.value.forEach(({marker, name, center, isWC, isStair, isBigDoor, isOtherDoor, doorNum, nickname, isParkingExit, isParkingEntrance}) => {
          const el = marker.getElement();
          if (el) {
            let show = false;
            let displayText = '';
            // 根据类型和缩放级别决定是否显示
            if (isBigDoor || isParkingExit || isParkingEntrance) {
              // 特定出入口和停车场标记始终显示，不受缩放级别限制
              show = true;
              displayText = name;
            } else if (isStair || isOtherDoor) {
              // 楼梯和普通出入口标记仅在缩放级别 >= 20 时显示
              show = zoom >= 20;
              displayText = isStair ? '楼梯' : name;
            } else if (isWC) {
              show = zoom >= 20; // WC在zoom >= 20时显示
              displayText = 'WC';
            } else if (nickname) {
              // 根据规范，如果nickname不为空，则始终显示，不受缩放级别限制
              show = true;
              displayText = nickname;
            } else {
              // ✅ 新的四级显示逻辑
              if (zoom >= 22) {         // 第 4 级 (22 ~ 23): 显示房间名称，这是最详细的一级
                displayText = name;
                show = true;
              } else if (zoom >= 21) {    // 第 3 级 (21 ~ 22): 同样显示房间名称，为最大级别做过渡
                displayText = name;
                show = true;
              } else if (zoom >= 20) {    // 第 2 级 (20 ~ 21): 显示房间门牌号
                displayText = doorNum;
                show = true;
              } else {                    // 第 1 级 (< 20): 不显示标签
                show = false;
              }
            }
            el.style.display = show ? 'block' : 'none';

            // 动态调整字体大小
            const fontSize = Math.max(8, Math.min(zoom * 0.8, 14));
            const iconWidth = Math.max(30, fontSize * 2.5);
            const iconHeight = fontSize + 4;
            let adjustedFontSize = fontSize;
            if (name.length > 6) {
              adjustedFontSize = Math.max(6, fontSize * 0.8);
            } else if (name.length > 4) {
              adjustedFontSize = Math.max(7, fontSize * 0.9);
            }

            // 在 handleZoomChange 函数中找到设置 marker.setIcon 的部分，替换为以下代码：

            marker.setIcon(L.divIcon({
              className: "label-class",
              html: isStair
                  ? `<div style=\"background:#fff;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:24px;height:24px;display:flex;align-items:center;justify-content:center;border:2px solid #4285F4;\"><img src=\"img/stair1.png\" style=\"width:14px;height:14px;display:block;\"  alt="public/img/stair1.png"/></div>`
                  : isBigDoor
                      ? `<div style=\"background:#fff;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:24px;height:24px;display:flex;align-items:center;justify-content:center;border:2px solid #4285F4;\"><img src=\"img/indoor.png\" style=\"width:14px;height:14px;display:block;\"  alt="public/img/indoor.png"/></div>`
                      : isOtherDoor
                          ? `<div style=\"background:#fff;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:24px;height:24px;display:flex;align-items:center;justify-content:center;border:2px solid #4285F4;\"><img src=\"img/indoor.png\" style=\"width:14px;height:14px;display:block;\" /></div>`
                          : isWC
                              ? `<div style=\"background:#fff;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:24px;height:24px;display:flex;align-items:center;justify-content:center;border:2px solid #43b244;\"><img src=\"img/WC.png\" style=\"width:14px;height:14px;display:block;\"  alt="public/img/WC.png"/></div>`
                              : isParkingExit
                                  ? `<div style=\"background:#fff;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:30px;height:30px;display:flex;align-items:center;justify-content:center;border:2px solid #4285F4;\"><img src=\"img/parkingLotOut.png\" style=\"width:22px;height:22px;display:block;\" /></div>`
                                  : isParkingEntrance
                                      ? `<div style=\"background:#fff;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.18);width:30px;height:30px;display:flex;align-items:center;justify-content:center;border:2px solid #4285F4;\"><img src=\"img/parkingLotIn.png\" style=\"width:22px;height:22px;display:block;\" /></div>`
                                      : `<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; color: black; font-size: ${adjustedFontSize * 1.2}px; font-weight: 500; writing-mode: vertical-lr; text-orientation: mixed;">${displayText}</div>`,
              iconSize: isStair || isBigDoor || isOtherDoor || isWC || isParkingExit || isParkingEntrance ? [30, 30] : [iconWidth, iconHeight],
              iconAnchor: isStair || isBigDoor || isOtherDoor || isWC || isParkingExit || isParkingEntrance ? [15, 15] : [iconWidth / 2, iconHeight / 2]
            }));


            el.style.fontSize = adjustedFontSize + 'px';
            el.style.maxWidth = iconWidth + 'px';
          }

          // 每次缩放时同步刷新 marker 的位置到单元面中心
          if (center && marker) {
            marker.setLatLng(center);
          }
        });

        // 同步刷新起点终点 marker 的位置到单元面中心，并同步更新 globalStartPoint/globalEndPoint
        updateMarkersOnMap();
      } catch (error) {
        console.error('处理缩放变化时发生错误:', error);
      }
    }

    function setEndPointFromRoom_click() {
      try {
        const clickedLayer = layers.danYuanMian.getLayers().find(layer => {
          console.log("终点房间:" , roomName.value)
          return String(layer.feature?.properties?.id) === String(roomId.value);
        });

        if (!clickedLayer) {
          console.error("未找到对应房间:", roomName.value);
          return;
        }

        const roomBounds = clickedLayer.getBounds();
        const roomCenter = roomBounds.getCenter();

        const pathGeoJSON = layers.routeLine.toGeoJSON();
        if (!pathGeoJSON || !pathGeoJSON.features) {
          console.error("路径数据无效");
          return;
        }

        const centerPoint = turf.point([roomCenter.lng, roomCenter.lat]);
        const pathPoints = turf.explode(pathGeoJSON);
        const nearestPoint = turf.nearestPoint(centerPoint, pathPoints);

        if (!nearestPoint?.geometry?.coordinates) {
          console.error("无法找到最近的路径点");
          return;
        }

        const [lng, lat] = nearestPoint.geometry.coordinates;

        // 确保 roomName 被正确设置
        const roomNameFromLayer = clickedLayer.feature.properties.name || '';
        roomName.value = roomNameFromLayer;

        // 更新全局终点
        globalEndPoint.value = {
          lat: Number(lat),
          lng: Number(lng),
          roomName: roomNameFromLayer,
          floor: currentFloor.value,
          doorNum: clickedLayer.feature.properties.doorNum || '',
        };

        // 更新显示数据
        endPointData.value = {
          roomName: roomNameFromLayer,
          floor: currentFloor.value
        };

        // 更新地图标记
        updateMarkersOnMap();

        showTipMessageDrawer.value = false;
        showNavigationDrawer.value = true;
      } catch (error) {
        console.error("设置终点失败:", error);
      }
    }

    return {
      refreshIcon,
      drawerHeight,
      onDrawerHeightChange,
      hideFloorSwitch,
      handleFloorChange,
      showTopDrawer,
      showBottomDrawer: showQuickEntryDrawer, // 这里直接用 computed
      showBottomDrawer2: showNavigationDrawer,
      showBottomDrawer3: showTipMessageDrawer,
      roomName,
      roomId,
      setEndPointFromRoom,
      startPointData,
      endPointData,
      pathDistance,
      pathDuration,
      clearPointsAndMarkers,
      switchToTargetFloor,
      pathTips,
      setRoomById,
      floorSwitchRef,
      bottomOffset,
      refreshPage,
      isSameFloor,
      currentRoomDoorNum,
      setEndPointFromRoom_click,
      handleBottomDrawer2HeightChange,
      checkUserLocationAndNavigate,
    };
  }
};
</script>

<style scoped>
/* 添加对竖排文字的支持 */
:deep(.label-class .vertical-text) {
  writing-mode: vertical-lr;
  text-orientation: mixed;
  text-align: center;
}

/* 如果你想让特定大小的文字竖直显示 */
:deep(.label-class.large-text) {
  writing-mode: vertical-lr;
  text-orientation: mixed;
  text-align: center;
  letter-spacing: 2px;
}

.home-root {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.leaflet-container {
  width: 100%;
  height: 100%;
  background: transparent;
  overflow: hidden;
  flex: 1 1 0;
  position: relative;
}

#map {
  width: 100%;
  height: 100%;
  touch-action: none;
  background-color: #edf4fa;
  background-image: linear-gradient(0deg, #e2e9ef 0.8px, transparent 1px),
  linear-gradient(90deg, #e2e9ef 0.8px, transparent 1px);
  background-size: 12px 12px;
}

.refresh-button {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 9999;
  background-color: white;
  border: 1px solid #ccc;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.refresh-button:hover {
  background-color: #f0f0f0;
}

.refresh-button img {
  width: 20px;
  height: 20px;
}

/* 指南针样式 */
.compass-container {
  position: absolute;
  top: 11px;
  right: 70px;
  z-index: 9999;
  width: 50px;
  height: 50px;
}

.compass {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2),
  inset 0 0 10px rgba(0, 0, 0, 0.1);
  border: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
}

.compass-direction {
  position: absolute;
  font-size: 9px;
  font-weight: bold;
  color: #333;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);
}

.compass-direction.n {
  top: 2px;
  font-size: 11px;
  color: #ff0000;
  font-weight: 900;
}

.compass-direction.e {
  right: 3px;
}

.compass-direction.s {
  bottom: 2px;
}

.compass-direction.w {
  left: 3px;
}

.compass-needle.north {
  position: absolute;
  width: 2px;
  height: 15px;
  background: linear-gradient(to top, #ff0000, #ff6666);
  bottom: 50%;
  transform-origin: bottom center;
  z-index: 2;
  border-radius: 2px 2px 0 0;
}

.compass-needle.south {
  position: absolute;
  width: 2px;
  height: 15px;
  background: linear-gradient(to bottom, #000000, #666666);
  top: 50%;
  transform-origin: top center;
  z-index: 2;
  border-radius: 0 0 2px 2px;
}

.compass-center {
  position: absolute;
  width: 6px;
  height: 6px;
  background: #333;
  border-radius: 50%;
  z-index: 3;
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
}

.compass::before {
  content: "";
  position: absolute;
  width: 24px;
  height: 24px;
  border: 1px solid rgba(0, 0, 0, 0.05);
  border-radius: 50%;
}

.compass::after {
  content: "";
  position: absolute;
  width: 16px;
  height: 16px;
  border: 1px solid rgba(0, 0, 0, 0.05);
  border-radius: 50%;
}

/* 添加标签样式 */
:deep(.label-class) {
  white-space: nowrap;
  overflow: visible;
  text-align: center;
  pointer-events: none;
  color: #333;
  text-shadow: 1px 1px 1px rgba(255, 255, 255, 0.8);
}

/* 路线动画样式 */
:deep(.animated-path) {
  stroke-dasharray: 10, 10; /* 虚线样式：10px实线，10px空白 */
  stroke-dashoffset: 0;
  animation: dash 1s linear infinite; /* 应用动画 */
}

@keyframes dash {
  from {
    stroke-dashoffset: 20; /* 动画开始时，偏移20px */
  }
  to {
    stroke-dashoffset: 0; /* 动画结束时，回到原点，形成循环 */
  }
}
</style>
